﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;

namespace Smugmug
{
    public static class Config
    {
        public static string ServiceVersion
        {
            get { return GetString("Smugmug.ServiceVersion", "1.2.2"); }
        }

        public static string ApiKey
        {
            get { return GetString("Smugmug.ApiKey", ""); }
        }

        public static string PasswordHash
        {
            get { return GetString("Smugmug.PasswordHash", ""); }
        }

        public static int? UserId
        {
            get { return GetInt32("Smugmug.UserId", null); }
        }

        public static string UserAgent
        {
            get { return GetString("Smugmug.UserAgent", ""); }
        }

        public static Dictionary<int, string> GetSavedAlbums()
        {
            var albums = new Dictionary<int, string>();
            string albumString = GetString("SavedAlbums", "");
            if (String.IsNullOrEmpty(albumString))
                return albums;
            string[] pairs = albumString.Split(',');
            foreach(string pair in pairs)
            {
                string[] parts = pair.Split(';');
                if(parts.Length > 1)
                {
                    int albumId;
                    if(Int32.TryParse(parts[0], out albumId))
                    {
                        albums.Add(albumId, parts[1]);
                    }
                }
            }
            return albums;
        }

        public static int? GetInt32(string key, int? defaultValue)
        {
            string s = ConfigurationManager.AppSettings[key];
            int val;
            if(Int32.TryParse(s, out val))
            {
                return val;
            }
            return defaultValue;
        }

        public static string GetString(string key, string defaultValue)
        {
            string s = ConfigurationManager.AppSettings[key];
            if(String.IsNullOrEmpty(s))
            {
                return defaultValue;
            }
            return s;
        }

        public static bool? GetBoolean(string key, bool? defaultValue)
        {
            string s = ConfigurationManager.AppSettings[key];
            bool val;
            if (Boolean.TryParse(s, out val))
            {
                return val;
            }
            return defaultValue;
        }
    }
}